package com.yunhe.sms.controller;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ResourceServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/11/14 0014 16:58
 * @Description: 异常捕捉
 */
@ControllerAdvice
public class ExceptionHandlerController {
    private static Logger log = LoggerFactory.getLogger(ResourceServlet.class);  //日志记录
    @ExceptionHandler
    public void exceptionHandler(Exception e, HttpServletRequest req,HttpServletResponse resp) throws IOException {
        boolean isAjax = ("XMLHttpRequest".equals(req.getHeader("X-Requested-with")));//判断ajkx是否存在
        log.info ( e.getStackTrace ().toString () );
        if (isAjax){
            HashMap<String, Object> map = new HashMap<> ();
            map.put ( "msg","出错了！" );
            writeJSON ( map,resp );
        }else{
            resp.sendError ( 500 );
        }
    }

    /**
     * 写入JSON
     * @param obj
     * @param resp
     * @throws IOException
     */
    public static void writeJSON(Object obj, HttpServletResponse resp) throws IOException {
        resp.setContentType ( "text/json" );
        String string = JSON.toJSONString ( obj );
        PrintWriter writer = resp.getWriter ();
        writer.write ( string );
        writer.close ();
    }
}
